package com.example.casper.jnuexperiment2025;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.casper.jnuexperiment2025.data.DataBank;
import com.example.casper.jnuexperiment2025.data.ShopItem;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ShopListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ShopListFragment extends Fragment {
    public ShopListFragment() {
        // Required empty public constructor
    }

    public static ShopListFragment newInstance() {
        ShopListFragment fragment = new ShopListFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_shop_list, container, false);
        addItemLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent data = result.getData();
                        assert data != null;
                        String name = data.getStringExtra("item name"); // 获取返回的数据
                        Double price = data.getDoubleExtra("item price",0); // 获取返回的数据
                        int position = data.getIntExtra("item position",0);

                        shopItems.add(position,new ShopItem(name, price, R.drawable.compute2));
                        shopItemsAdapter.notifyItemInserted(position);
                        DataBank dataBank= new DataBank();
                        dataBank.save(shopItems,this.getContext());

                    } else if (result.getResultCode() == Activity.RESULT_CANCELED) {
                        // 处理取消操作
                    }
                }
        );
        updateItemLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent data = result.getData();
                        assert data != null;
                        String name = data.getStringExtra("item name"); // 获取返回的数据
                        Double price = data.getDoubleExtra("item price",0); // 获取返回的数据
                        int position = data.getIntExtra("item position",0);

                        ShopItem shopItem= shopItems.get(position);
                        shopItem.setName(name);
                        shopItem.setPrice(price);
                        shopItemsAdapter.notifyItemChanged(position);
                        DataBank dataBank= new DataBank();
                        dataBank.save(shopItems,this.getContext());

                    } else if (result.getResultCode() == Activity.RESULT_CANCELED) {
                        // 处理取消操作
                    }
                }
        );
        shopItems= (new DataBank()).load(this.getContext());
        if(shopItems.isEmpty())
        {
            shopItems.add(new ShopItem("test item",1.5,R.drawable.compute1));
        }
        RecyclerView shopRecyclerView = rootView.findViewById(R.id.recyclerview_main_list);
        shopRecyclerView.setLayoutManager(new LinearLayoutManager(this.getContext()));
        shopItemsAdapter = new ShopItemsAdapter(shopItems);
        shopRecyclerView.setAdapter(shopItemsAdapter);

        registerForContextMenu(shopRecyclerView);

        return rootView;
    }

    private ArrayList<ShopItem> shopItems = new ArrayList<ShopItem>();
    ActivityResultLauncher<Intent> addItemLauncher;
    ActivityResultLauncher<Intent> updateItemLauncher;
    private ShopItemsAdapter shopItemsAdapter;

    private void showDeleteConfirmationDialog(int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this.getContext());
        builder.setTitle("确认删除");
        builder.setMessage("您确定要删除此项吗？删除后数据将无法恢复。"+position);

        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 用户点击确认后，在此处执行删除数据的操作
                shopItems.remove(position);
                shopItemsAdapter.notifyItemRemoved(position);
                DataBank dataBank= new DataBank();
                dataBank.save(shopItems,ShopListFragment.this.getContext());
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss(); // 关闭对话框
            }
        });
        builder.show();
    }

    @Override
    public boolean onContextItemSelected(MenuItem menuItem) {
        //item.getOrder()
        switch (menuItem.getItemId()) {
            case 0: {
                Intent intent = new Intent(this.getActivity(), ShopItemActivity.class);
                intent.putExtra("item position", menuItem.getOrder());
                addItemLauncher.launch(intent);
                break;
            }
            case 1: {
                Intent intent = new Intent(this.getActivity(), ShopItemActivity.class);
                intent.putExtra("item position", menuItem.getOrder());
                intent.putExtra("item name", shopItems.get(menuItem.getOrder()).getName());
                intent.putExtra("item price", shopItems.get(menuItem.getOrder()).getPrice());
                updateItemLauncher.launch(intent);
                break;
            }
            case 2:
                showDeleteConfirmationDialog(menuItem.getOrder());
                break;
            default:
                return super.onContextItemSelected(menuItem);
        }
        return true;
    }
    public static class ShopItemsAdapter extends RecyclerView.Adapter<ShopItemsAdapter.ViewHolder> {

        private final ArrayList<ShopItem> localDataSet;

        /**
         * Provide a reference to the type of views that you are using
         * (custom ViewHolder)
         */
        public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
            private final TextView textViewItemName;
            private final TextView textViewItemPrice;
            private final ImageView imageViewItem;

            public ViewHolder(View viewRowRoot) {
                super(viewRowRoot);
                // Define click listener for the ViewHolder's View

                textViewItemName = viewRowRoot.findViewById(R.id.textview_shop_item_name);
                textViewItemPrice = viewRowRoot.findViewById(R.id.textview_shop_item_price);
                imageViewItem = viewRowRoot.findViewById(R.id.image_view_item);

                viewRowRoot.setOnCreateContextMenuListener(this);
            }
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v,
                                            ContextMenu.ContextMenuInfo menuInfo) {
                menu.setHeaderTitle("具体操作");

                menu.add(0, 0, this.getAdapterPosition(), "添加" + this.getAdapterPosition());
                menu.add(0, 1, this.getAdapterPosition(), "更新" + this.getAdapterPosition());
                menu.add(0, 2, this.getAdapterPosition(), "删除" + this.getAdapterPosition());
            }

            public TextView getTextViewItemName() {
                return textViewItemName;
            }

            public TextView getTextViewItemPrice() {
                return textViewItemPrice;
            }

            public ImageView getImageViewItem() {
                return imageViewItem;
            }
        }

        /**
         * Initialize the dataset of the Adapter
         *
         * @param dataSet String[] containing the data to populate views to be used
         * by RecyclerView
         */
        public ShopItemsAdapter(ArrayList<ShopItem> dataSet) {
            localDataSet = dataSet;
        }

        int viewHolderCount=0;
        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            // Create a new view, which defines the UI of the list item
            View viewRowRoot = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.shop_item_row, parent, false);

            viewHolderCount++;
            Log.i("Hello05692#RecyclerView",viewHolderCount+"created");
            return new ViewHolder(viewRowRoot);
        }

        // Replace the contents of a view (invoked by the layout manager)
        @Override
        public void onBindViewHolder(ViewHolder viewHolder, final int position) {

            // Get element from your dataset at this position and replace the
            // contents of the view with that element
            viewHolder.getTextViewItemName().setText(localDataSet.get(position).getName());
            viewHolder.getTextViewItemPrice().setText(String.format("%s", localDataSet.get(position).getPrice()));
            viewHolder.getImageViewItem().setImageResource(localDataSet.get(position).getDrawableId());
        }

        // Return the size of your dataset (invoked by the layout manager)
        @Override
        public int getItemCount() {
            return localDataSet.size();
        }
    }
}